package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.AnnexVo;
import com.zb.entity.ZjUser;
import com.zb.entity.ZjUserAnnex;
import com.zb.mapper.ZjUserAnnexMapper;
import com.zb.service.ZjUserAnnexService;
import com.zb.service.ZjUserService;
import com.zb.vo.UserAnnexVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户附件表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-11-15
 */
@Service
public class ZjUserAnnexServiceImpl extends ServiceImpl<ZjUserAnnexMapper, ZjUserAnnex> implements ZjUserAnnexService {
    @Resource
    private ZjUserService userService;

    // 新增或删除用户附件
    @Override
    public void save(Long userId, UserAnnexVo userAnnexVo) {
        if (CollectionUtil.isNotEmpty(userAnnexVo.getDelAnnexIds())) {
            this.removeByIds(userAnnexVo.getDelAnnexIds());
        }
        if (CollectionUtil.isEmpty(userAnnexVo.getAnnexVos())) {
            return;
        }
        ZjUser user = userService.getById(userId);
        Assert.isTrue(null != user, "客户ID参数[ "+ userId +" ]的客户数据不存在");
        List<ZjUserAnnex> adds = new ArrayList<>();
        List<ZjUserAnnex> updates = new ArrayList<>();
        ZjUserAnnex annex = null;
        for (AnnexVo vo : userAnnexVo.getAnnexVos()) {
            annex = new ZjUserAnnex();
            BeanUtil.copyProperties(vo, annex);
            if (null != annex.getId()) {
                updates.add(annex);
                continue;
            }
            annex.setId(IdWorker.getId());
            annex.setCustAccId(user.getCustAccId());
            annex.setUserId(userId);
            adds.add(annex);
        }
        if (CollectionUtil.isNotEmpty(adds)) this.saveBatch(adds);
        if (CollectionUtil.isNotEmpty(updates)) this.updateBatchById(updates);
    }

    // 根据客户ID获取客户附件
    @Override
    public List<AnnexVo> getUserAnnex(Long userId) {
        QueryWrapper<ZjUserAnnex> wrapper = new QueryWrapper<>();
        wrapper.select("id", "path");
        wrapper.eq("user_id", userId);
        return this.list(wrapper).stream().map(an -> {
            return new AnnexVo(an.getId(), an.getPath());
        }).toList();
    }
}
